#coding=utf8

# 导入系统模块
import os
import logging
import traceback
from logging.handlers import RotatingFileHandler
# 导入自定义库
import commlib.Constant as COMMC

class Logger(object):
    """docstring for ClassName"""

    def __init__(self, logPath = "", logType = "main", logName = "", logLevel = logging.DEBUG):

        #self.outputFormat = '[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s]:%(message)s'
        self.outputFormat = '[%(asctime)s][%(levelname)s]:%(message)s'
        self.outputDateFmt = '%Y-%m-%d %H:%M:%S'

        # 统一初始化，不然输出到屏幕的可能就不会存在这个参数
        self.Rthandler = None

        # 基础不变的
        self.logger = logging.getLogger(logType)
        self.logger.setLevel(logLevel)

        # 初始化存储文件位置
        self.init_file_logger(logPath, logType, logName)

    def init_file_logger(self, logPath, logType, logName):
        """
        初始化文件记录形式的日志系统
        """
        # 判断日志目录是否存在，若不存在，则创建之
        if not os.path.exists(logPath) :
            os.makedirs(logPath, mode=0770)

        # 拼接存储文件名
        if logName:
            outputFile = os.path.join(logPath, '.'.join([logType, logName, 'log']))
        else:
            outputFile = os.path.join(logPath, logType+'.log')

        # 初始化logging日志配置
        self.Rthandler = RotatingFileHandler(outputFile, maxBytes=100*1024*1024, backupCount=5)
        self.Rthandler.setFormatter(logging.Formatter(self.outputFormat, self.outputDateFmt))
        self.logger.addHandler(self.Rthandler)

    @staticmethod
    def _init_defaulut_logger(fnwithpath=None, level=logging.DEBUG, maxsize=100, maxcount=5):
        """
        初始化系统的默认日志系统
        """
        # 初始化日志级别
        logger = logging.getLogger()
        logger.setLevel(level)

        # 初始化日志内容格式
        contentFmt = '[%(asctime)s][%(levelname)s]: %(message)s'
        datetimeFmt = '%Y-%m-%d %H:%M:%S'
        formatter = logging.Formatter(contentFmt, datetimeFmt)

        # 初始化logging日志配置，判断是否是写入到文件模式
        if fnwithpath:
            # 校验目录是否存在
            logpath = os.path.dirname(fnwithpath)
            if not os.path.exists(logpath) :
                os.makedirs(logpath, mode=0770)
            # 日志句柄
            logHandler = RotatingFileHandler(fnwithpath, maxBytes=maxsize*1024*1024, backupCount=maxcount)
        else:
            logHandler = logging.StreamHandler()

        logHandler.setFormatter(formatter)
        logger.addHandler(logHandler)
        # 输出当前日志级别信息
        logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))
        
        return logging

    @staticmethod
    def init_defaulut_logger(filename, level=logging.DEBUG, maxsize=100, maxcount=5):
        """
        初始化日志系统
        """
        if COMMC.LOGGER_OUT_TYPE == "console":
            Logger._init_defaulut_logger(None, level, maxsize, maxcount)
        else:
            fnwithpath = COMMC.LOG_SERVICE_PATH + filename
            Logger._init_defaulut_logger(fnwithpath, level, maxsize, maxcount)

    # 关闭原先的日志文件记录
    def close(self):
        # 先移除再关闭
        try:
            self.logger.removeHandler(self.Rthandler)
            self.Rthandler.close()
            self.Rthandler = None
        except:
            print(traceback.format_exc())

    def write(self, msg):
        self.logger.info(msg)

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)


